package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.Mapper.SpecGroupMapper;
import com.leyou.item.Mapper.SpecParamMapper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SpecService {

    @Autowired(required = false)
    private SpecGroupMapper groupMapper;

    @Autowired(required = false)
    private SpecParamMapper paramMapper;

    public List<SpecGroup> findSpecGroupByCid(Long id) {

        //1.封装条件
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);

        QueryWrapper<SpecGroup> query = Wrappers.query(specGroup);

        //2.执行查询，获取结果
        List<SpecGroup> specGroups = groupMapper.selectList(query);

        //3.处理结果，返回结果
        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return specGroups;
    }

    public List<SpecParam> findSpecParams(Long gid, Long cid, Boolean searching) {
        //1.封装条件
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);

        QueryWrapper<SpecParam> query = Wrappers.query(specParam);

        //2.执行查询，获取结果
        List<SpecParam> specParams = paramMapper.selectList(query);

        //3.处理结果，返回结果
        if(CollectionUtils.isEmpty(specParams)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return specParams;
    }

    public List<SpecGroupDTO> findSpecGroupAndParams(Long cid) {

        try {
            //1.查询规格组
            List<SpecGroup> specGroupList = this.findSpecGroupByCid(cid);
            //2.拷贝数据
            List<SpecGroupDTO> specGroupDTOList = BeanHelper.copyWithCollection(specGroupList,SpecGroupDTO.class);
            //3.封装组内参数
            specGroupDTOList.forEach(specGroupDTO -> {
                //4.查询组内参数
                List<SpecParam> specParams = this.findSpecParams(specGroupDTO.getId(),null,null);
                specGroupDTO.setParams(specParams);
            });
            return specGroupDTOList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
    }
}
